from PySide6.QtWidgets import QApplication, QMessageBox
from PySide6.QtCore import  Qt,QTimer,QCoreApplication,QThread
from PySide6.QtGui import QPixmap

from pygame import mixer

import random
import time
import math
import sys
from pathlib import Path
if hasattr(sys, '_MEIPASS'):
    # 打包后，基础路径是临时解压目录
    root_path = Path(sys._MEIPASS)
else:
    # 开发时，基础路径是当前文件所在目录
    root_path = Path(__file__).parent

class MusicThread(QThread):

    def __init__(self, file_path, parent=None):
        super().__init__(parent)
        self.file_path = file_path
        self.is_playing = False
        self._stop_requested = False
        
    def run(self):
        """线程主函数"""
        try:
            # 初始化pygame mixer
            if not mixer.get_init():
                mixer.init(frequency=44100, size=-16, channels=2, buffer=1024)
            
            # 加载并播放音频
            mixer.music.load(self.file_path)
            mixer.music.play()
            self.is_playing = True
            
            # 等待播放完成或被中断
            while self.is_playing and not self._stop_requested:
                if not mixer.music.get_busy():
                    self.is_playing = False
                    self.playback_finished.emit()
                else:
                    self.msleep(100)  # 避免忙等待
                    
        except Exception as e:
            self.playback_error.emit(f"播放错误: {str(e)}")
        finally:
            # 清理资源
            if mixer.get_init():
                mixer.music.stop()
                mixer.quit()
    
    def stop_playback(self):
        """停止播放"""
        self._stop_requested = True
        self.is_playing = False
        
    def pause_playback(self):
        """暂停播放"""
        if self.is_playing and mixer.get_init():
            mixer.music.pause()
    
    def resume_playback(self):
        """恢复播放"""
        if mixer.get_init():
            mixer.music.unpause()
    
    def set_volume(self, volume):
        """设置音量 (0.0 到 1.0)"""
        if mixer.get_init():
            mixer.music.set_volume(max(0.0, min(1.0, volume)))
        

class show_care:
    def __init__(self):
        music_path = root_path / "background_music.MP3"

        print(music_path)
        self.music_thread = MusicThread(music_path)
        self.music_thread.start()
        self.init_create_msg()

# region 弹窗初始化
    def init_create_msg(self):
        self.dialog_num = 150
        self.msg_list = []
        self.available_grid_positions = self._create_screen_grid(self.dialog_num)

        self.name = "xxx"
        self.What_I_want_to_say = [
            "降温了，你的外套够暖吗？","看你最近有点疲惫，是有什么烦心事吗？\n我都在",
            "知道你忙，但也要记得按时吃饭呀","累的时候，允许自己当个小孩，歇一歇吧",
            "你喜欢的那个口味，我刚好路过，给你带了一份","小小休息是为了更好的出发\n继续加油吧",
            "身体是革命的本钱\n照顾好自己比啥都重要","雨天慢行，带伞了吗？\n别让雨水淋湿了你的心情",
            "把疲惫留给昨天吧，轻松迎接夜晚的宁静","心里事儿太多就说出来嘛\n我一直在这里倾听你的心声",
            "寒冷冬日，有你真暖和，感谢一路陪伴和支持","平凡的日子也要闪闪发光\n每一天都值得被认真对待",
            "虽然距离遥远但心意相通\n想你的时候空气都是甜的","这些天辛苦了","有没有要帮忙的？",
            "别怕，慢慢来\n我就在旁边","你已经做得很好了\n别太苛责自己",
            "这件事确实不容易，换成是我也会觉得难","无论结果如何\n你都不是一个人面对",
            "我们一起想想办法？\n或许能换个角度看看","这次没达到预期\n但你积累的经验特别宝贵",
            "压力大的时候\n记得你背后还有我们","照顾别人的时候\n也别忘了心疼自己",
            "只要今天比昨天强就好！","别怕，你肯定能行！","只要努力，下次就一定能考好",
            "尽管很难，但你一直没有放弃","你做事情的态度非常不错！",
            "你一点都不怕困难，太难得了！","没关系，一切都会好起来的！"
        ]

        self.color = [
            "#FFB6C1","#FFFFC3","#87CEFA","#AFEEEE", 
            "#FFC0CB","#ADD8E6","#CBFFFF","#FFDAB9", 
            "#FFA07A","#C9C9FF","#FF8295","#FE9DAB"  
        ]
        self.dialog_process(self.dialog_num)

# region 平分屏幕
    def _create_screen_grid(self, grid_count):
        """将屏幕平均分成指定数量的网格，并返回所有网格的中心点坐标"""
        screen = QApplication.primaryScreen()
        screen_geometry = screen.size()
        screen_width = screen_geometry.width()
        screen_height = screen_geometry.height()
        
        # 计算网格的行列数（尽量接近正方形）
        grid_cols = int(grid_count ** 0.5)
        grid_rows = (grid_count + grid_cols - 1) // grid_cols
        
        # 计算每个网格的实际大小
        grid_width = screen_width // grid_cols
        grid_height = screen_height // grid_rows
        
        grid_positions = []
        
        # 计算所有网格的中心点坐标
        for row in range(grid_rows):
            for col in range(grid_cols):
                if len(grid_positions) >= grid_count:
                    break
                
                # 计算网格中心点坐标
                center_x = col * grid_width + grid_width // 2
                center_y = row * grid_height + grid_height // 2
                
                grid_positions.append((center_x, center_y))
            
        return grid_positions

# region 弹窗动作流程
    def dialog_process(self, num):
        # 随机创建弹窗
        for _ in range(num):
            self.create_msg()
            time.sleep(0.1)
            QApplication.processEvents()

        # 稍微弹窗堵塞一下
        self.wait_for_msg()

        # 变成粉色
        self.change_color("#FF8295")

        # 摆成爱心
        self.arrange_hearts_shape()

        # 自动关闭
        QTimer.singleShot(1000, self.exit_application)

# region 创建弹窗
    def create_msg(self):
        message = self.What_I_want_to_say[random.randint(0, len(self.What_I_want_to_say)-1)]
        color = self.color[random.randint(0, len(self.color)-1)]
        msg = QMessageBox(QMessageBox.Information,self.name,message)
        self.msg_list.append(msg)

        msg.setStyleSheet(f"""
            QMessageBox {{ 
                background-color: {color}; 
                font-size: 18px; 
            }}
            QMessageBox QLabel {{ 
                font-size: 18px; 
            }}
        """)
        transparent_pixmap = QPixmap(1, 1)
        transparent_pixmap.fill(Qt.transparent)
        msg.setIconPixmap(transparent_pixmap)  

        msg.setStandardButtons(QMessageBox.StandardButton.NoButton) 
        msg.setWindowModality(Qt.NonModal)

        if self.available_grid_positions:
            # 随机选择一个网格位置
            center_x, center_y = random.choice(self.available_grid_positions)
            # 从列表中移除该位置，确保不重复
            self.available_grid_positions.remove((center_x, center_y))
            
            # 获取弹窗的推荐大小
            suggested_size = msg.sizeHint()
            msg_width = suggested_size.width()
            msg_height = suggested_size.height()

            # 计算弹窗左上角坐标，使其居中于网格中心点
            x = max(0, center_x - msg_width // 2)
            y = max(0, center_y - msg_height // 2 )

            
            # 确保弹窗不超出屏幕边界
            screen = QApplication.primaryScreen()
            screen_geometry = screen.size()
            x = min(x, screen_geometry.width() - msg_width)
            y = min(y, screen_geometry.height() - msg_height)
            
            msg.move(x, y)
        
        msg.show() 

# region 等待弹窗
    def wait_for_msg(self):
        msg=QMessageBox(QMessageBox.Information,self.name,"没关系，一切都会好起来的！")
        msg.setStyleSheet(f"""
            QMessageBox {{ 
                background-color: #FF8295; 
                font-size: 18px; 
            }}
            QMessageBox QLabel {{ 
                font-size: 18px; 
            }}
        """)
        transparent_pixmap = QPixmap(1, 1)
        transparent_pixmap.fill(Qt.transparent)
        msg.setIconPixmap(transparent_pixmap)  
        msg.setWindowModality(Qt.WindowModal)
        msg.exec()
# region 颜色变粉色
    def change_color(self,color):
        for msg in self.msg_list:
            msg.setStyleSheet(f"""
                QMessageBox {{ 
                    background-color: {color}; 
                }}
                QMessageBox QLabel {{ 
                    font-size: 18px; 
                }}
            """)
        QApplication.processEvents()
        time.sleep(0.5)

# region 爱心形状
    def arrange_hearts_shape(self):
        """将弹窗排列成爱心形状 - 优化版：增大爱心、增加弹窗、提升性能"""
        screen = QApplication.primaryScreen()
        screen_geometry = screen.size()
        screen_width = screen_geometry.width()
        screen_height = screen_geometry.height()
        
        # 动态设置弹窗数量和大小：基于屏幕分辨率调整
        popup_width, popup_height = 80, 80  # 可调整为80x80以增大弹窗
        max_points = min(len(self.msg_list), 200)  # 增加弹窗数量上限至500
        num_points = min(max_points, 200)  # 确保不超过合理上限
        
        # 预计算心形点：移出循环，提升性能
        heart_points = []
        for i in range(num_points):
            t = 2 * math.pi * i / num_points
            x_eq = 16 * (math.sin(t) ** 3)
            y_eq = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t)
            heart_points.append((x_eq, y_eq))
        
        # 计算爱心中心点和缩放因子（增大爱心尺寸）
        center_x = screen_width // 2
        center_y = screen_height // 2
        if heart_points:
            x_vals = [point[0] for point in heart_points]
            y_vals = [point[1] for point in heart_points]
            max_x = max(abs(val) for val in x_vals)
            max_y = max(abs(val) for val in y_vals)
            # 增大缩放比例：使用屏幕的85%而非60%，使爱心更大
            scale_x = (screen_width * 0.85) / (max_x * 2) if max_x > 0 else 100
            scale_y = (screen_height * 0.85) / (max_y * 2) if max_y > 0 else 100
            scale = min(scale_x, scale_y)
        else:
            scale = 100  # 默认值提高以增大爱心

        for i, msg in enumerate(self.msg_list):
            msg.hide()
            if i < len(heart_points):
                # 计算位置（翻转y轴）
                point_x, point_y = heart_points[i]
                x = center_x + point_x * scale - popup_width // 2
                y = center_y - point_y * scale - popup_height // 2
                x = max(0, min(x, screen_width - popup_width))
                y = max(0, min(y, screen_height - popup_height))
                msg.setText("")
                msg.setFixedSize(popup_width, popup_height)
                msg.move(int(x), int(y))

        QApplication.processEvents()


        # 排列弹窗
        for i, msg in enumerate(self.msg_list):
            if i < len(heart_points):
                msg.show()
                QApplication.processEvents()
            else:
                msg.hide()  # 隐藏多余弹窗

            time.sleep(0.05)

# region 关闭弹窗
    def exit_application(self):
        total_msgs = len(self.msg_list)
        for i in range((total_msgs + 1) // 2):
            # 隐藏左边的消息（从开头开始）
            if i < len(self.msg_list):
                self.msg_list[i].hide()
            
            # 隐藏右边的消息（从结尾开始）
            right_index = total_msgs - 1 - i
            if right_index > i and right_index < len(self.msg_list):
                self.msg_list[right_index].hide()

            time.sleep(0.07)

        QApplication.processEvents()
        self.msg_list.clear()
        self.music_thread.stop_playback()
        QCoreApplication.exit(0) 


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = show_care()


    sys.exit(app.exec())